<template>
  <div id="empAuthDep">
    <el-form
      :model="empAuthDepartForm"
      :rules="empAuthDepartFormRule"
      ref="empAuthDepartFormRef"
      class="form-input-m"
      label-width="80px"
      :inline="true"
      inline-message
      @submit.native.prevent
    >
      <el-form-item label="选择部门" prop="deptId">
        <!-- <el-popover title="点击选择部门" v-model="visibleDept" trigger="click" placement="right"> -->
        <!-- <SelectByDepList ref="deptBySelect" @selectDeptByClick="selectDept" /> -->
        <el-select
          placeholder="请选择部门"
          :teleported="false"
          v-model="empAuthDepartForm.deptId"
          filterable
          style="width: 200px;"
        >
          <el-option
            v-for="dept in deptOptions"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          ></el-option>
        </el-select>
        <!-- @keyup.enter.native="onEnterSelectDept" -->
        <!-- </el-popover> -->
      </el-form-item>

      <el-form-item class="elFormItemClazz">
        <el-button type="primary" plain @click="handleAddAuthdept()">添加</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="danger" plain @click="deleteAllAuthdepts">删除全部</el-button>
      </el-form-item>
    </el-form>

    <el-table
      class="empAuthDeptTable"
      ref="employAuthDeptsTable"
      v-loading="eLoading"
      row-key="id"
      :data="employAuthDeptsList"
      style="width: 100%"
      highlight-current-row
      max-height="330px"
      min-height="330px"
    >
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="deptCode" label="部门编号" min-width="100"></el-table-column>
      <el-table-column prop="deptName" label="部门名称" min-width="100"></el-table-column>
      <el-table-column prop="isDefault" label="是否默认" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isDefault"
            disabled
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" min-width="110" align="center">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" content="设置为默认？" placement="top-start">
            <el-button
              :type="scope.row.isDefault === '0' ? 'success' : ''"
              icon="Star"
              size="small"
              circle
              @click="setDefaultDepart(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-button
            type="danger"
            icon="delete"
            plain
            size="small"
            circle
            @click="deleteAuthdeptById(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="dialog-footer1 flex justify-end">
      <el-button @click="closePerDialog('empAuthDepartForm')">关闭</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import SelectByDepList from '@/components/SelectByDepList.vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

// let visibleDept = ref(false);
let employAuthDeptsList: any = reactive([]); //表格数据
let eLoading = ref(false); //表格数据加载状态
let deptOptions: any = reactive([]); //选择框

let deptvalue = ref(''); //select接收值

// let pageIndex = ref(1);
// let pageSize = PageSizeList[0];

let empAuthDepartForm = reactive({
  id: '', //要生成的id
  deptId: '', //部门id
  deptName: '',
  deptCode: ''
});

const empAuthDepartFormRule = {
  deptName: [
    {
      required: true,
      message: '请选择部门',
      trigger: 'blur'
    }
  ],
  deptId: [
    {
      required: true,
      message: '请选择部门',
      trigger: 'blur'
    }
  ]
};

// 接收传过来的机构和部门id
let childIds = reactive({
  orgId: '',
  deptId: ''
});

let employeeId = ''; //接收传过来的员工id

// 方法定义区 =============
//暴露属性和方法
defineExpose({
  init
});

function init(item: any) {
  // console.log('父组件传给授权部门子组件的机构和部门', item);
  if (item.id) {
    // 机构和部门id
    childIds.orgId = item.orgId;
    childIds.deptId = item.deptId ? item.deptId : '';
    employeeId = item.id; //员工id
  }
}

// 改变下拉框标题
function changeTitle(val: any) {
  empAuthDepartForm.id = val;
}

// 页面加载时
proxy.$nextTick(() => {
  findAuthDepartsById(employeeId); //表格已选部门
  getDepyOptions(); //下拉框所有部门
});

// 获取所有部门选项(下拉框)
function getDepyOptions() {
  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { orgId: childIds.orgId } })
    .then((res: any) => {
      deptOptions.push(...res.data.deptList);
    })
    .catch((err: any) => {
      VxeMessage('获取所有部门选项(下拉框)失败', VxeNotifyType.error);
    });
}

// 获取当前员工已关联的部门(表格)
function findAuthDepartsById(employeeId: any) {
  // 员工id
  if (employeeId) {
    const url = '/api/sys/hisEmployee/getDeptListByHisEmployeeId/' + employeeId;
    proxy.$http
      .get(url)
      .then((res: any) => {
        employAuthDeptsList.length = 0;
        employAuthDeptsList.push(...res.data);
      })
      .catch((err: any) => {
        // VxeMessage('获取当前员工已关联部门失败','error')
      });
  }
}

//点击选择的那一项部门
function selectDept(row: any) {
  //   this.empAuthDepartForm.deptId = row.id;
  //   this.empAuthDepartForm.deptName = row.name;
  //   const selectDeptEle: any = this.$refs.selectDept;
  //   selectDeptEle.focus();
  //   this.visibleDept = false;
}
//选择部门的输入框改变
function bindDeptList(value: any) {
  //   const deptBySelect: any = this.$refs.deptBySelect;
  //   deptBySelect.deptForm.name = value;
  //   deptBySelect.pageIndex = 1;
  //   deptBySelect.findDeptList();
}
//选择部门的输入框获取焦点
function showDeptList(e: any) {
  //   const deptBySelect: any = this.$refs.deptBySelect;
  //   deptBySelect.deptForm.name = this.empAuthDepartForm.deptName;
  //   deptBySelect.pageIndex = 1;
  //   deptBySelect.findDeptList();
}

// 添加关联部门
function handleAddAuthdept() {
  const $el = proxy.$refs.empAuthDepartFormRef;
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    //  //部门id 员工id
    employAuthDeptsList.length = 0;
    eLoading.value = true;
    const url =
      '/api/sys/hisEmployee/addContactDeptInfo/' + employeeId + '/' + empAuthDepartForm.deptId;
    proxy.$http
      .put(url)
      .then((res: any) => {
        if (res.status.code === 1) {
          findAuthDepartsById(employeeId);
          empAuthDepartForm.id = '';
          empAuthDepartForm.deptId = '';
          empAuthDepartForm.deptName = '';
          empAuthDepartForm.deptCode = '';
          deptvalue.value = ''; //清空选择框
          // VxeMessage(res.status.msg, VxeNotifyType.success);
          VXETable.modal.message({
            content: '添加一个关联部门成功',
            status: 'success'
          });
          eLoading.value = false;
        } else {
          VXETable.modal.message({
            content: '添加一个关联部门失败',
            status: 'error'
          });
          // VxeMessage('添加关联部门失败', VxeNotifyType.error);
          eLoading.value = false;
        }
      })
      .catch((err: any) => {
        VxeMessage('添加关联部门接口异常', VxeNotifyType.error);
        eLoading.value = false;
      });
  });
}

// 删除一个
const deleteAuthdeptById = async (id: any) => {
  const type = await VXETable.modal.confirm('您确定要删除这个关联部门吗？');
  if (type === 'cancel') {
    // VXETable.modal.message({
    //   status: 'info',
    //   content: `点击了${type == 'cancel' ? '取消' : '确定'}`
    // });
  } else {
    employAuthDeptsList.length = 0;
    // 部门id 删除一个
    const url = '/api/sys/hisEmployee/deleteDeptContactById/' + id + '/0';
    proxy.$http
      .delete(url)
      .then((res: any) => {
        if (res.status.code === 1) {
          VXETable.modal.message({
            content: '删除一个关联部门成功',
            status: 'success'
          });
        } else {
          VXETable.modal.message({
            content: '删除一个关联部门失败',
            status: 'error'
          });
        }
        findAuthDepartsById(employeeId);
      })
      .catch((err: any) => {
        // VXETable.modal.message({
        //   content: '删除一个关联部门接口失败',
        //   status: 'error'
        // });
        // VxeMessage('删除一个关联部门异常', VxeNotifyType.error);
      });
  }
};

// 设置默认部门
function setDefaultDepart(row: any) {
  const authUrl = '/api/sys/hisEmployee/setDefaultDeptByHisEmployeeId/' + row.id + '/' + employeeId;
  proxy.$http
    .put(authUrl)
    .then((res: any) => {
      VxeMessage('修改成功', VxeNotifyType.success);
      findAuthDepartsById(employeeId);
    })
    .catch((err: any) => {
      VxeMessage('修改失败', VxeNotifyType.error);
    });
}

// 删除全部
const deleteAllAuthdepts = async () => {
  const type = await VXETable.modal.confirm('您确定要删除此员工关联的全部部门吗？');
  if (type === 'cancel') {
    // VXETable.modal.message({
    //   status: 'info',
    //   content: `点击了${type == 'cancel' ? '取消' : '确定'}`
    // });
  } else {
    employAuthDeptsList.length = 0;
    // 部门id 删除一个
    const url = '/api/sys/hisEmployee/deleteDeptContactById/' + employeeId + '/1';
    proxy.$http
      .delete(url)
      .then((res: any) => {
        findAuthDepartsById(employeeId);
        if (res.status.code === 1) {
          VXETable.modal.message({
            content: '删除此员工的全部关联部门成功',
            status: 'success'
          });
          // VxeMessage('删除此员工的全部关联部门成功', VxeNotifyType.success);
        } else {
          VXETable.modal.message({
            content: '删除此员工的全部关联部门失败',
            status: 'error'
          });
          // VxeMessage('删除此员工的全部关联部门失败', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除此员工的全部关联部门异常', VxeNotifyType.error);
      });
  }
};

// 关闭弹框
function closePerDialog(formName: any) {
  let $el = proxy.$refs.empAuthDepartFormRef;
  proxy.$emit('closePerDialog');
}
</script>
<style lang="scss" scoped>
#empAuthDep {
  height: 100%;
  position: relative;
  .elFormItemClazz {
    margin-right: 10px;
  }
  .dialog-footer1 {
    position: absolute;
    bottom: 5px;
    right: 10px;
  }
}
</style>
